package com.example.aliyun.plus.sync;
class MyThreadA implements Runnable{
    private int ticket = 10; // 票总数


    @Override
    public void run() {
        while (this.saled()){
            /*
            synchronized (this) { // 同步代码块
                if (this.ticket > 0){
                    try {
                        Thread.sleep(100);
                        System.out.println(Thread.currentThread().getName() +"  卖票--------> " + this.ticket--);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else {
                    System.out.println("===================票已经卖光了======================");
                    break;
                }
            }
             */
        }
    }

    private synchronized boolean saled() {
        if (this.ticket > 0){
            try {
                Thread.sleep(100);
                System.out.println(Thread.currentThread().getName() +"  卖票--------> " + this.ticket--);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                return true;
            }
        }else {
            System.out.println("===================票已经卖光了======================");
            return false;
        }
    }
}

public class ThreadSycSolved {
    public static void main(String[] args) {
        MyThreadA myThread = new MyThreadA();
        Thread threadA = new Thread(myThread, "票贩子A");
        Thread threadB = new Thread(myThread, "票贩子B");
        Thread threadC = new Thread(myThread, "票贩子C");
        threadA.start();
        threadB.start();
        threadC.start();
    }
}
